package com.myres.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPTool {

    public String compress(String plain) throws IOException {
    	ByteArrayOutputStream baos=new ByteArrayOutputStream();
    	GZIPOutputStream gop=new GZIPOutputStream(baos);
    	gop.write(plain.getBytes());
    	gop.finish();
    	baos.close();
        return baos.toString("ISO-8859-1");
    }
    public String constract(String zipdata) throws IOException{
    	ByteArrayInputStream bais=new ByteArrayInputStream(zipdata.getBytes("ISO-8859-1"));
    	GZIPInputStream gip=new GZIPInputStream(bais);
    	byte[] buf=new byte[512];
    	int len=0;
    	ByteArrayOutputStream baos=new ByteArrayOutputStream();
    	while((len=gip.read(buf, 0, buf.length))!=-1){
    		baos.write(buf, 0, len);
    	}
    	gip.close();
    	bais.close();
    	return baos.toString("GBK");
    }
    
    public static void main(String[] args){
    	try{
    	GZIPTool tool=new GZIPTool();
    	String o="测试";
    	System.out.println(o);
    	String zipData=tool.compress(o);
    	System.out.println("zip="+zipData);
    	String plain=tool.constract(zipData);
        System.out.println("plain="+plain);
    	}catch(IOException e){
    		e.printStackTrace();
    	}
    	
    }
}
